import json

from sqlalchemy import Column, Integer, String, CHAR, DECIMAL
from models.base import db
import time

from models.base import Base


class Sentence(Base):
    __tablename__ = 'sentence'
    id = Column(Integer, primary_key=True, autoincrement=True)
    order_number = Column(String(30), nullable=False)
    sentence_index = Column(Integer, nullable=False)
    content = Column(String(150), nullable=False)
    paragraph_index = Column(Integer, nullable=False)
    is_similar = Column(Integer, nullable=False, default=0)
    rate = Column(DECIMAL(5, 2), default=0)
    suggest = Column(String(2000), default='')
    is_author = Column(Integer, default=0)
    check_content = Column(String(2000), default='')
    check_id = Column(Integer, default=0)

    @classmethod
    def get_sentence(cls, paragraph_index, order_number):
        result = db.query(cls).filter_by(order_number=order_number, paragraph_index=paragraph_index).order_by(
            'id').all()
        return result

    def sentence_count(self, order_number):
        result = db.query(Sentence).filter_by(order_number=order_number).count()
        return result

    def get_similar_sentences(self, order_number):
        result = db.query(Sentence).filter_by(order_number=order_number).filter(Sentence.is_similar != 0).all()
        return result

    def sentence_codebar(self, order_number):
        results = db.query(Sentence).filter_by(order_number=order_number).all()
        codebar = []
        for item in results:
            if item.is_similar == 1:
                codebar.append(2)
            elif item.is_similar == 2:
                codebar.append(1)
            else:
                codebar.append(0)
        return [codebar]

    def sentence_suggest(self, order_number, sentence_index):
        res = db.query(Sentence).filter_by(order_number=order_number).filter_by(sentence_index=sentence_index).first()
        if res.suggest == '':
            return []
        else:
            try:
                return json.loads(res.suggest)
            except:
                return []
